package com.yyt.springbootdemoredis.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * 使用z-set实现排行榜功能
 * 除此命令之外 还有
 * 1、
 * ZUNIONSTORE
 * 命令格式： zunionstore destkey numkeys member [member]
 * 功能：并集运算
 * <p>
 * 2、
 * ZINTERSTORE
 * 命令格式： zinterstore destkey numkeys key [key]
 * 功能：交集运算
 *
 * @author yeyangtao
 * @since 2022/9/8 14:52
 */
@RestController
public class TopController {
    private static final String TOP_ZSET_KEY = "top";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("get/top/list")
    public Object getTopList() {
        Set<Object> set = redisTemplate.opsForZSet().reverseRange(TOP_ZSET_KEY, 0, 9);

        Map<String, Double> map = new LinkedHashMap<>();
        for (Object o : set) {
            map.put(o.toString(), redisTemplate.opsForZSet().score(TOP_ZSET_KEY, o));
        }
        return map;
    }

    @PostMapping("set")
    public void set(String title, double score) {
        redisTemplate.opsForZSet().add(TOP_ZSET_KEY, title, score);
    }

    @DeleteMapping("del")
    public void del(@RequestParam Object[] titles) {
        redisTemplate.opsForZSet().remove(TOP_ZSET_KEY, titles);
    }

    @PostMapping("increment")
    public void increment(String title, double score) {
        redisTemplate.opsForZSet().incrementScore(TOP_ZSET_KEY, title, score);
    }
}
